<template>
  <div class="app-container"  id="taskManagement">
    <ContentWrap >
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="任务编号" prop="taskNo">
        <el-input
          v-model="queryParams.taskNo"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="任务时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="date"
          range-separator="-"
          placeholder="选择时间"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="报警状态" prop="status">
        <el-select v-model="queryParams.status"  clearable placeholder="请选择报警状态">
          <el-option
            v-for="dict in dict.type.task_management_task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['swla2:taskManagement:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['swla2:taskManagement:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['swla2:taskManagement:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['swla2:taskManagement:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="managementList"
      @selection-change="handleSelectionChange"
       border :height="getAvailableHeight"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="id" /> -->
      <el-table-column label="序号"   type="index" :index="calculateIndex" width="55" align="center"/>
      <el-table-column label="任务编号" align="center" prop="taskNo" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务地址" align="center" prop="taskAddress" />
      <el-table-column
        label="任务开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="任务结束时间"
        align="center"
        prop="endTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime ) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="desc">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.task_management_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>

      <el-table-column label="负责人" align="center" prop="header" />
      <el-table-column label="报警状态" align="center" prop="taskStatus">
        
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.taskStatus"
            type="text"
            @click="handleTaskDetail(scope.row.taskNo)"
          >
         
            <dict-tag
            :options="dict.type.task_management_task_status"
            :value="scope.row.taskStatus"
              />
          </el-button>
          <label v-else>暂无任务状态</label>
        </template>

      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['swla2:taskManagement:edit']"
            >修改</el-button
          >
           <el-button
            size="mini"
            type="text"
            icon="el-icon-set-up"
            @click="handleSetting(scope.row)"
            v-hasPermi="['swla2:taskManagement:edit']"
            >挂接</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['swla2:taskManagement:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="810px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号" prop="taskNo">
              <el-input v-model="form.taskNo" placeholder="请输入任务编号"  :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label=" 任务地址" prop="taskAddress">
              <el-input
              type="text"
                v-model="form.taskAddress"
                placeholder="请输入任务地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select
                :size="formItemSizeAdd"
                v-model="form.status"
                placeholder="请选择状态"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.task_management_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :selected="dict.value === '0'"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人" prop="header">
              <el-input v-model="form.header" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="telephone">
              <el-input v-model="form.telephone" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="任务开始时间" prop="startTime">
              <el-date-picker
                :size="formItemSizeAdd"
                v-model="form.startTime"
                type="datetime"
                placeholder="请选择任务开始时间"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务结束时间" prop="endTime">
              <el-date-picker
                :size="formItemSizeAdd"
                v-model="form.endTime"
                type="datetime"
                placeholder="请选择任务结束时间"
                style="width: 100%"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="任务描述" prop="desc">
          <el-input
            v-model="form.desc"
            type="textarea"
            placeholder="请输入任务描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


     <!-- 挂接 -->
    <el-dialog :title="setTitle" :visible.sync="setOpen" width="680px" :close-on-click-modal="false" append-to-body>
      <div style="height: 400px;">
        <el-form ref="setForm" label-width="0px" style="display: flex;"> 
          <el-form-item label="" prop="">
            <el-button type="primary" plain icon="el-icon-plus" @click="handleTerminalAdd" >新增</el-button>
          </el-form-item>
          <el-form-item label="" prop="" style="margin-left: 10px;">

            <el-input
              type="text"  @change="handleEnergyTypeChange"
              clearable
                v-model="terminalQueryParams.deviceNum"
                placeholder="请输入设备编号"
              />

              <el-input
              type="hidden"  
                v-model="terminalQueryParams.taskManagementId"
              />
          </el-form-item>
        </el-form>
        <el-table v-loading="setLoading" :data="setDataList" size="mini" row-key="id" border height="calc(100% - 50px)">

          <el-table-column label="序号"  type="index" width="80" /> 
          <el-table-column label="任务编号" align="center" prop="taskNo" width="120" /> 
          <el-table-column label="任务名称" align="center" prop="taskName" width="120" /> 
          <el-table-column label="设备编号" align="center" prop="deviceNum" width="120" /> 
          
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleBindTerminalDelete(scope.row)"
                >
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>


    <!-- 挂接-新增按钮弹框 -->
    <el-dialog title="选取设备" :visible.sync="terminalOpen" width="720px" :close-on-click-modal="false" append-to-body>
      <div style="height: 400px;">
        <el-form ref="terminalForm" :model="terminalQueryParamsAdd" label-width="70px" style="display: flex;"> 

          <el-form-item label="设备编号" prop="terminalId" style="margin-left: 10px;">
            <el-input :size="formItemSizeAdd" v-model="terminalQueryParamsAdd.deviceNum" placeholder="请输入设备编号" clearable />
          </el-form-item>
          <div style="margin-left: 10px;height: 30px;line-height: 36px;">
            <el-button  type="primary" plain icon="el-icon-search" @click="handleTerminalQuery" size="mini">查询</el-button>
          </div>
        </el-form>
        <el-table v-loading="terminalLoading" :data="terminalDataList" size="mini" row-key="id" border height="calc(100% - 102px)"
          @selection-change="handleSelectionChange2">
          <el-table-column type="selection" width="60" align="center"/>
          <el-table-column label="序号"   type="index" :index="calculateIndexAdd" width="80" align="center"/>
          <el-table-column label="设备编号" align="center" prop="deviceNum" width="160" />
          <el-table-column label="安装时间" align="center" prop="installTime" width="160" />
          <el-table-column label="安装区域" align="center" prop="installPosition" width="200" />

        </el-table>
        <pagination
          v-show="terminalTotal>0"
          :total="terminalTotal"
        
          :page.sync="terminalQueryParamsAdd.pageNum"
          :limit.sync="terminalQueryParamsAdd.pageSize"
          layout="total, sizes, prev, pager, next"
          @pagination="getTerminalDataList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="terminalSubmitForm">确 定</el-button>
        <el-button @click="terminalCancel">取 消</el-button>
      </div>
    </el-dialog>

  </ContentWrap>

  </div>
</template>

<script>
import { getManagement, listManagement ,addManagement ,updateManagement
    , delManagement } from "@/api/leakage/taskManagement";

import { listForGJ ,delDetail  ,addTaskDetailList} from "@/api/leakage/taskDetail";
import { listForGJAddLedger } from "@/api/leakage/deviceLedger";


export default {
  name: "Management",
  dicts: ["task_management_status", "task_management_task_status","task_detail_monitor_status"],
  data() {
    var validateEndTime = (rule, value, callback) => {
        const { startTime } = this.form;
        // 若结束时间为空，直接通过（非空校验单独处理）
        if (!value) {
          return callback();
        }
        // 若开始时间为空，提示先选择开始时间
        if (!startTime) {
          return callback(new Error("请先选择开始时间"));
        }
        // 转换为时间戳比较（注意：字符串格式需一致，如 "YYYY-MM-DD HH:mm:ss"）
        const start = new Date(startTime).getTime();
        const end = new Date(value).getTime();
        if (end <= start) {
          callback(new Error("结束时间必须晚于开始时间"));
        } else {
          callback(); // 校验通过
        }
      };
    return {
      screenHeight:"",
      // 弹出层标题
      setTitle: "",
      // 是否显示弹出层
      setOpen: false,
      powerType:'1',
      setLoading:false,
      setDataList:[],
      selectedPublicShareId:null,
      selectedPublicShareName:'',
      terminalOpen:false,
      terminalTotal:0,
      terminalQueryParams:{
        pageNum: 1,
        pageSize: 2000,
        taskManagementId:'',
        // userId:'',
        // userName:''
      },
       terminalQueryParamsAdd:{
        pageNum: 1,
        pageSize: 20,
        taskManagementId:'',
        // userId:'',
        // userName:''
      },
      terminalLoading:false,
      terminalDataList:[],
      selectedTerminalList:[],


      selectedTaskId:null,
      selectedTaskNo:'',
      selectedTaskAddress:'',

      //////////////////////////////////////////////////
      // isEdit: false,
      
      formItemSizeAdd: "default",
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      taskNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务管理表格数据
      managementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskNo: null,
        taskName: null,
        taskAddress: null,
        desc: null,
        status: null,
        header: null,
        telephone: null,
        startTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskNo: [
          { required: true, message: "任务编号不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "状态不能为空",
            trigger: "change,blur",
          },
        ],
        startTime: [
          {
            required: true,
            message: "任务开始时间不能为空",
            trigger: "blur",
            // validator: this.validateStartTime,
          },
        ],
        endTime: [
          {
            required: true,
            message: "任务结束时间不能为空",
            trigger: "blur",
            // validator: this.validateEndTime,
          },
          { validator: validateEndTime, trigger: "blur" }, // 绑定自定义校验
        ],
      },
    };
  },
  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight
  },
   computed: {
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? 240 : 195)
    },
    // 计算两个周期值
		isEdit: function () {
			return  "修改任务管理" == this.title;
		},
  },

  methods: {
    handleTaskDetail(_taskNo){
       this.$router.push({ path: '/leak/taskDetail',query: { taskNo: _taskNo }})
    },
    calculateIndex(index) {
      // index 是当前页的行索引（从 0 开始）
      // 返回值为最终显示的序号
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    calculateIndexAdd(index) {
      // index 是当前页的行索引（从 0 开始）
      // 返回值为最终显示的序号
      return (this.terminalQueryParamsAdd.pageNum - 1) * this.terminalQueryParamsAdd.pageSize + index + 1;
    },


    /** 挂接start */
    //查询设备台账数据
    handleTerminalQuery(){
      this.getTerminalDataList();
    },
    /** 设备台账提交按钮 */
    terminalSubmitForm() {
      addTaskDetailList(this.selectedTerminalList).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getBindList();
              this.terminalOpen = false;
            });
    },
    // 多选框选中数据
    handleSelectionChange2(selection) {
      let that = this;
      that.selectedTerminalList = [];
      for(let i=0;i<selection.length;i++){
        let item = selection[i];
        that.selectedTerminalList.push({
          taskManagementId:that.selectedTaskId,
          // terminalId:item.terminalId,
          // userId:item.userId,
          deviceId:item.id,
          taskNo:that.selectedTaskNo,
          taskAddress:that.selectedTaskAddress,
          // status: 1
        });
      }
    },
    // 设备取消按钮
    terminalCancel() {
      this.terminalOpen = false;
      this.terminalQueryParamsAdd = {pageNum: 1,
        pageSize: 20,
        // userId:'',
        // userName:''
        taskManagementId:'',
      };
    },
    /** 区域设备配置-新增打开弹框 */
    handleTerminalAdd() {
      this.terminalQueryParamsAdd = {pageNum: 1,
        pageSize: 20,
        // userId:'',
        // userName:''
        taskManagementId:'',
      };
      this.terminalOpen = true;
      this.getTerminalDataList();
    },
    getTerminalDataList(){
      this.terminalLoading = true;
      this.terminalQueryParamsAdd.taskManagementId = this.selectedTaskId 
      listForGJAddLedger(this.terminalQueryParamsAdd).then(response => {
          this.terminalDataList = response.rows;
          this.terminalTotal = response.total;
          this.terminalLoading = false;
        });
    },
    // 区域设备配置
    handleSetting(row){
      this.setTitle="任务编号-"+row.taskNo+"挂接";
      this.setOpen = true;
      this.selectedTaskId = row.id;
      this.selectedTaskNo = row.taskNo;
      this.selectedTaskAddress = row.taskAddress;
      this.terminalQueryParams.taskManagementId = row.id;
      this.getBindList();


    },
    /** 删除按钮操作-区域设备配置 */
    handleBindTerminalDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除所选记录？').then(function () {
        return delDetail(id);
      }).then(() => {
        this.getBindList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // handleChange1(val){
    //   this.powerType = val+'';
    //   console.log(this.powerType);
    // },
    //区域设备配置-选择能耗类型
    handleEnergyTypeChange(val){
      this.getBindList();
    },
    getBindList(){
      //加载数据
      this.setLoading = true;
      // listUserTerminalsxbJoin({publicShareId:this.selectedPublicShareId,energyType:this.powerType}).then(response => {
      listForGJ(this.terminalQueryParams).then(response => {
         this.setDataList = [];
        if(response.rows){
          this.setDataList = response.rows;
        }
        this.setLoading = false;
      });
    },
    // handleEditChange(row){
    //   updateUserTerminalsxbJoin(row).then(response => {
    //       this.$modal.msgSuccess("修改成功");
    //       this.getBindList();
    //   });
    // },
    /** 挂接end */



    /** 查询任务管理列表 */
    getList() {
      this.loading = true;

      listManagement(this.queryParams).then(
        (response) => {
          this.managementList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dateRange = [];
      this.form = {
        id: null,
        taskNo: null,
        taskName: null,
        taskAddress: null,
        desc: null,
        status: null,
        taskStatus: null,
        header: null,
        telephone: null,
        startTime: null,
        endTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.taskNos = selection.map((item) => item.taskNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getManagement(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务管理";
      });
    },

    //   // 区域设备配置
    // handleSetting(row){
    //   this.setTitle="["+row.taskName+"]任务挂接";
    //   this.setOpen = true;
    //   // this.selectedPublicShareId = row.id;
    //   // this.selectedPublicShareName = row.publicShareName;
    //   // this.getBindList();

    //   this.selectedUserXbId = row.userId;
    //   this.selectedUserXbName = row.userName;
    //   this.getBindList();
    // },


    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateManagement(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addManagement(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const taskNos = row.taskNo || this.taskNos;
      this.$modal
        .confirm('是否确认删除任务管理编号为"' + taskNos + '"的数据项？')
        .then(function () {
          return delManagement(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "swla2/taskManagement/export",
        {
          ...this.queryParams,
        },
        `任务管理_${this.parseTime(new Date().getTime(), '{y}-{m}-{d}')}.xlsx`
      );
    },
  },
  // computed: {
		
  // }
};
</script>
